package com.douwong.student.popuwindow;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.NetConfig;
import com.douwong.student.model.AppVersion;
import com.douwong.student.model.StatusCode;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.UIUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * 版本升级
 * 
 * @author leihuajie
 * 
 */
public class AppVersionUpdate {

	private AppVersion appVersion;
	private Context context;
	private boolean isFirst = true;// true 表示从 main 进入 false 表示从设置进入
	private final int NEW_VERSION = 1;
	private final int NO_NEW_VERSION = -1;
	private final int UPDATE_PRO = 2;
	private final int UPDATE_COMPLETE = 3;
	private final int LOAD_ERROR = 4;
	private final int ACCESS_ERROR=5;
	private long length;
	private View view;
	private VersionUpdatePopuwindow popu;

	public AppVersionUpdate(Context context, View view) {
		this.context = context;
		this.view = view;
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == NEW_VERSION) {
				try {
					doNewVersionUpdate(context);// 有新版本
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				
			} else if (msg.what == NO_NEW_VERSION) {
				if (!isFirst) {
					try{
						notNewVersionShow(context);// 没有新版本
					}catch(Exception e){
						e.printStackTrace();
					}
					
				}
			} else if (msg.what == UPDATE_PRO) {// 更新下载进度
				popu.setProgress(msg.arg1 * 100 / (int) length);
			} else if (msg.what == UPDATE_COMPLETE) {// 下载完成
				popu.dismiss();
				update();

			} else if (msg.what == LOAD_ERROR) {
				Toast.makeText(context, "下载错误！", Toast.LENGTH_LONG).show();
				popu.dismiss();
			    if(appVersion!=null){
			    	File file = new File(FileUtils.APK_DIR, appVersion.getVuFileName());
			    	if(file!=null&&file.exists()){
			    		file.delete();
			    	}			    	
			    }
				

			}else if(msg.what==ACCESS_ERROR){
				Toast.makeText(context, "网络异常，请稍后再试！", Toast.LENGTH_LONG).show();
			}

		};
	};

	private String TAG = getClass().getSimpleName();

	// 得到当前的版本
	public int getCurrentVersion(Context context) {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			Log.e(TAG, e.getMessage());
		}
		return verCode;
	}

	// 得到当前的版本名称
	public String getCurrentVersionName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e(TAG, e.getMessage());
		}
		return verName;
	}

	/**
	 *  
	 * @param app Application
	 * @param isFirst true 一般为应用启动时调用，静默检查，false 将会把检查接口提示给用户
	 */
	public void checkVersionUpdate(BaseApplication app, final boolean isFirst) {
		this.isFirst = isFirst;		
		if (NetUtils.NetwrokIsUseful(UIUtils.getContext())) {
			new Thread() {
				@Override
				public void run() {
					
					try{						
						ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
						params.add(new BasicNameValuePair("vuType", "737"));
						
						String result = NetUtils.httpGet(NetConfig.VERSION_INFOR, params);
						Log.i("version", result);
						StatusCode<AppVersion> sc = (StatusCode<AppVersion>) JSON.parseObject(result,
								new TypeReference<StatusCode<AppVersion>>() {
								});
						if (sc != null && sc.isFlag()) {
							appVersion = sc.getData();
						}
						int currentVC=getCurrentVersion(context);
						Log.i(TAG, "versionCode : "+currentVC);
						if (appVersion!=null&&(appVersion.getVuCode() > currentVC)) {
							Message message = handler.obtainMessage();
							message.what = NEW_VERSION;
							handler.sendMessage(message);
						} else {
							Message message = handler.obtainMessage();
							message.what = NO_NEW_VERSION;
							handler.sendMessage(message);
					   }					
						
					}catch(Exception e){
						e.printStackTrace();
						
						if(!isFirst){
							Message message = handler.obtainMessage();
							message.what = ACCESS_ERROR;
							handler.sendMessage(message);
						}
						
				   }
					
				}

			}.start();
		}
	}

	private void notNewVersionShow(Context context) {
		popu = new VersionUpdatePopuwindow(context, false, 0);		
		popu.showAtLocation(view, Gravity.CENTER, 0, 0);
	}

	private void doNewVersionUpdate(final Context context) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			FileUtils.APK_DIR = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/douwong/apks";
			File apkDir=new File(FileUtils.APK_DIR);
			if(!apkDir.exists()){
				apkDir.mkdirs();
			}
			popu = new VersionUpdatePopuwindow(context, true, appVersion.getIsForce());
			popu.showAtLocation(view, Gravity.CENTER, 0, 0);
			if (appVersion.getIsForce() == 1) {
				downFile(appVersion.getDownloadUrl());
			} else {
				popu.setOnClick(new OnClick() {

					@Override
					public void onClick() {
						downFile(appVersion.getDownloadUrl());
					}
				});
			}
		}else{
			if(!isFirst){
				Toast.makeText(context,"本地存储设备异常，无法下载保存！！",Toast.LENGTH_LONG).show();
			}
		}
	}

	private void downFile(final String url) {
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					length = entity.getContentLength();
					InputStream is = entity.getContent();
									
					File file = new File(FileUtils.APK_DIR, appVersion.getVuFileName());
					
					if(file!=null&&file.exists()){
						//本地已经存在文件
						if(file.length()==length){
							Message message = handler.obtainMessage();
							message.what = UPDATE_COMPLETE;
							handler.sendMessage(message);
							return;
						}else{
							file.delete();
						}
						
					}else{
						//处理文件夹下的.apk文件
						File folder=new File(FileUtils.APK_DIR);
						File[] files=folder.listFiles(new FileFilter() {
							
							@Override
							public boolean accept(File pathname) {
								// TODO Auto-generated method stub
								return pathname.isFile();
							}
						});
						
						for(File file2:files){
							if(file2.getName().endsWith(".apk")){
								file2.delete();
							}
						}
						
					}
					
					FileOutputStream fileOutputStream = new FileOutputStream(file);
					byte[] buf = new byte[5120];
					int ch = -1;
					int count = 0;
					while ((ch = is.read(buf)) != -1) {
						fileOutputStream.write(buf, 0, ch);
						count += ch;
						Message message = handler.obtainMessage();
						message.what = UPDATE_PRO;
						message.arg1 = count;
						handler.sendMessage(message);							
					}
					fileOutputStream.flush();
					fileOutputStream.close();
					is.close();
					Message message = handler.obtainMessage();
					message.what = UPDATE_COMPLETE;
					handler.sendMessage(message);
				} catch (Exception e) {
					Message message = handler.obtainMessage();
					message.what = LOAD_ERROR;
					handler.sendMessage(message);
					e.printStackTrace();
				}
			}
		}.start();
	}

	public interface OnClick {
		void onClick();
	}

	// 重新安装应用
	@SuppressLint("InlinedApi")
	@SuppressWarnings("deprecation")
	private void update() {
		try {
			Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
			intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
			intent.putExtra(Intent.EXTRA_ALLOW_REPLACE, true);
			intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, context.getApplicationInfo().packageName);
			intent.setData(Uri.fromFile(new File(FileUtils.APK_DIR, appVersion.getVuFileName())));
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}
